<?php

namespace HelloWeb\UserBundle\Service\User;

use Doctrine\ORM\EntityManager;
use HelloWeb\UserBundle\Entity\User;
use HelloWeb\UserBundle\Entity\Repository\UserRepository;
use Symfony\Component\DependencyInjection\Container;

class UserService
{

    /** @var Container */
    protected $container;

    /** @var EntityManager */
    protected $entityManager;

    /** @var UserRepository */
    protected $userRepository;

    /**
     * Resolve dependencies
     * @param EntityManager $entityManager
     * @param Container $container
     */
    public function __construct(
        EntityManager $entityManager, 
        Container $container)
    {
        $this->container = $container;
        $this->entityManager = $entityManager;
        $this->userRepository = $entityManager->getRepository("HelloWebUserBundle:User");
    }

    /**
     * Get a User Object by given criteria
     * @param array $criteria
     * @return User
     */
    public function getUser($criteria)
    {
        return $this->userRepository->findOneBy($criteria);
    }

    /**
     * Get all available users
     * @param array $searchArray
     * @param bool $allowDeactive
     * @param bool $allowDeleted
     * @return null|User[]
     */
    public function getAllUsers(
        $searchArray = array(), 
        $allowDeactive = false, 
        $allowDeleted = false)
    {
        return $this->userRepository->fetchAll(
            $searchArray, 
            $allowDeactive, 
            $allowDeleted);
    }

    /**
     * Save the given user entity
     * @param User $user
     */
    public function saveUser(User $user)
    {
        // Immediate persist
        $this->entityManager->persist($user);
        $this->entityManager->flush();
    }
}